<!-- 访视管理 -->
<template>
  <div>
    <!-- 操作栏 -->
    <div style="display: flex; margin-bottom: 14px">
      <!-- <a-descriptions title="访视管理"></a-descriptions> -->
      <a-button
        v-if="$auth('PROJECT.PROJECT_VISIT_ADD')"
        type="primary"
        icon="plus"
        @click="actionAdd()"
      >添加版本</a-button
      >
      <a-button :href="'/payment/muban/访视导入模板.xlsx'|dealImageUrl" style="margin: 0 12px;" v-if="$auth('PROJECT.PROJECT_VISIT_ADD')">模板下载</a-button>
      <a-upload
        accept=".xlsx"
        name="file"
        list-type="picture"
        :customRequest="file=>clickImport(file)"
        @change="handleChange"
        :fileList="fileList"
        class="flex1"
      >
        <a-button type="default" v-if="$auth('PROJECT.PROJECT_VISIT_ADD')">导入访视版本</a-button>
      </a-upload>
    </div>
    <a-tabs v-if="$auth('PROJECT.PROJECT_VISIT_LIST')" tab-position="left">
      <template v-for="item in tabs">
        <a-tab-pane :key="item.id" :tab=" item.status ? '版本' + item.name + '(启动)': '版本' + item.name + '(停用)' " @tabClick="activeVisitId(item.id)">
          <!-- 表格开始 -->
          <a-table :columns="columns" bordered :data-source="item.visitVersionList" :pagination="false">
            <template slot="title">
              <!-- 标题 -->
              <a-descriptions :title="'版本' + item.name"></a-descriptions>
              <!-- 启用禁用开关 -->
              <div class="flex-center">
                <a-switch
                  v-model="item.status"
                  checked-children="启动"
                  un-checked-children="停用"
                  default-checked
                  v-if="$auth('PROJECT.PROJECT_VISIT_STATUS')"
                  @change="handleSwitch(item.status, item.id)"
                />
                <div>
                  <a-button @click="activeEdit(item.id, item.visitVersionList)" v-if="$auth('PROJECT.PROJECT_VISIT_EDIT')">编辑</a-button>
                  <a-button @click="clickExport(item.id)" style="margin-left: 12px" icon="download" v-if="$auth('PROJECT.PROJECT_VISIT_EXPORT')">导出</a-button>
                  <!-- <a-upload
                    accept=".xlsx"
                    name="file"
                    list-type="picture"
                    :customRequest="file=>clickImport(file, item.id)"
                    @change="handleChange"
                    :fileList="fileList"
                    class="flex1"
                  >
                    <a-button type="default">导入</a-button>
                  </a-upload> -->
                </div>
              </div>
            </template>
          </a-table>
        </a-tab-pane>
      </template>
    </a-tabs>
    <!-- 新增访视组件 -->
    <AddVisitModal
      ref="addVisitModal"
      :modalTitle="modalTitle"
      :visible="visible"
      @ok="handleOk"
      @cancel="visible = false"
      :recordId="recordId"
    ></AddVisitModal>
  </div>
</template>

<script>
// import monitor from '@/utils/monitor'
import { exportExcel } from '@/utils/util'
// import overview from '@/monitor/overview/Detail-Responsible/Visit'
import AddVisitModal from './addVisitModal.vue'
// import { list, add, updata, updataEdit, getExportExl } from '@/api/overview/visit'
import { list, add, updata, updataEdit, getVisitExport, visitImport } from '@/api/overview/visit'

// const watch = monitor(overview)
const columns = [
  {
    title: '访视序号',
    dataIndex: 'orderNumber'
  },
  {
    title: '访视名词',
    dataIndex: 'name'
  },
  {
    title: '访视阶段',
    dataIndex: 'stage'
  },
  {
    title: '距离基线或随机时间',
    dataIndex: 'rangeTime'
  },
  {
    title: '访视窗',
    dataIndex: 'windowPeriod'
  },
  {
    title: '访视地点',
    dataIndex: 'address'
  }
]
export default {
  name: '',
  components: {
    AddVisitModal
  },
  data () {
    return {
      exportId: 0,
      visible: false, // 访视标识
      tabs: [],
      visitId: '',
      columns,
      modalTitle: '',
      recordId: '',
      fileList: []
    }
  },
  mounted () {
    this.getList()
  },
  // methods: watch({
  methods: {
    getList () {
      list({
        proId: this.$route.query.id
      }).then(res => {
        console.log(res)
        this.tabs = res
        this.tabs.forEach(item => {
          if (item.visitVersionList && item.visitVersionList.length > 0) {
            for (let index = 0; index < item.visitVersionList.length; index++) {
              item.visitVersionList[index].orderNumber = index + 1
            }
          }
        })
      })
    },
    // 新增
    actionAdd () {
      this.visible = true
      this.recordId = ''
      this.modalTitle = '添加访视计划'
      this.$refs.addVisitModal.isEdit = false
    },
    // 编辑
    activeEdit (id, list) {
      this.modalTitle = '编辑访视计划'
      this.visitId = id
      this.recordId = id
      const obj = this.$refs.addVisitModal
      const tableData = JSON.parse(JSON.stringify(list))
      tableData.forEach(item => {
        item.key = item.id
        item.editable = false
        item.isNew = true
        delete item.modifyTime
        delete item.createTime
        delete item.version
        delete item.visitVersionId
        delete item.deleted
        delete item.vno
      })
      obj.data = [] // 每次进入先清空
      obj.isEdit = true // 打开编辑标识
      obj.data = tableData
      this.visible = true
      console.log('tableData', tableData)
    },
    // 弹框OK回调
    handleOk (param) {
      const visitRecordList = param
      if (!this.$refs.addVisitModal.isEdit) {
        add({
          proId: this.$route.query.id,
          visitRecordList
        }).then(res => {
          this.$message.success('操作成功！')
          this.getList() // 刷新数据
          this.visible = false
        })
      } else {
        updataEdit({
          id: this.visitId,
          visitRecordList
        }).then(res => {
          this.$message.success('操作成功！')
          this.getList() // 刷新数据
          this.visible = false
        })
      }
      this.$refs.addVisitModal.data = []
    },
    // 导出表格
    clickExport (id) {
      getVisitExport({ versionId: id })
        .then(res => {
          exportExcel('访视', res)
        })
        .catch(() => {})

      // getExportExl({ 'versionId': id }).then((res) => {
      //   exportExcel('excel', res)
      // })
      // console.log(id)
      // versionId
      // const parseParams = (url, params) => {
      //   const paramsArray = []
      //   Object.keys(params).forEach(key => params[key] && paramsArray.push(`${key}=${params[key]}`))
      //   if (url.search(/\?/) === -1) {
      //     url += `?${paramsArray.join('&')}`
      //   } else {
      //     url += `&${paramsArray.join('&')}`
      //   }
      //   return url
      // }
      // const baseUrl = '/api'
      // const api = '/boss/project/visit/export'
      // const fullUrl = baseUrl + api
      // console.log(fullUrl)
      // const dealUrl = parseParams(fullUrl, id)
      // console.log(this.queryParam)
      // window.open(dealUrl, '_blank')
    },
    // 处理switch回调
    handleSwitch (flag, id) {
      console.log(flag)
      let status = null
      flag ? (status = 1) : (status = 0)
      updata({
        id,
        status
      }).then(res => {
        console.log(res)
        this.$message.success('操作成功！')
      })
    },
    handleChange (info) {
      const fileList = [...info.fileList]
      this.fileList = fileList
    },
    clickImport ({ file }, id = null) {
      const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isJpgOrPng) {
        this.$notification.error({
          message: file.name,
          description: '仅支持文件格式: .xlsx 格式文件!'
        })
        return false
      } else {
        const params = new FormData()
        params.append('file', file)
        id ? params.append('versionId', id) : params.append('proId', this.$route.query.id)
        return visitImport(params).then(res => {
          this.$notification.success({
            message: file.name,
            description: '上传成功'
          })
          setTimeout(() => {
            this.fileList = []
          }, 1500)
          this.getList()
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
.ant-tabs .ant-tabs-left-bar .ant-tabs-tab,
.ant-tabs .ant-tabs-right-bar .ant-tabs-tab {
  padding: 8px 64px;
}
.flex-center {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.flex1{
  flex: 1;
}
</style>
